function OutputTurboEnc = TurboEncode(g, InMess, pos);

% generator polynomials parameters
[n,K] = size(g);
% number of states
m = K-1;

% set the states to zero
state = zeros(1,m);

[b,length]=size(InMess);
outputenc11=[];
outputenc12=[];
outputenc22=[];
%h=number of input bits
for x=1:length+m
    if x<=length
        mes=InMess(1,x);
    else
        mes=rem(g(1,2:K)*(state)',2);
        % the output 1 feed back
    end
    
    input=rem(g(1,:)*([mes state])',2);

    for i=1:n
        output(i) = g(i,1)*input;
        for j = 2:K
            temp=g(i,j)*state(j-1);
            output(i) = xor(output(i),temp);
        end;
    end
    state = [input, state(1:m-1)];


    % concatenation new element
    %outputenc1=[outputenc1,mes,output(2)];
    outputenc11=[outputenc11,mes];
    outputenc12=[outputenc12,output(i)];
    
end



% encoder 2

for x=1:length+m
    interleavmes=outputenc11(1,pos(1,x));

    % the output 1 feed back
    input=rem(g(1,:)*([interleavmes state])',2);
    for i=1:n
        output(i) = g(i,1)*input;
        for j = 2:K
            temp=g(i,j)*state(j-1);
            output(i) = xor(output(i),temp);
        end;
        %keep last output(1)
        if i==1
            temp1=output(i);
        end
    end
    state = [input, state(1:m-1)];
    % concatenation new element
    outputenc22=[outputenc22,output(2)];
end
OutputTurboEnc = [ outputenc11; 
                   outputenc12;
                   outputenc22 ];